import React, { memo, useState, useEffect, useRef, useCallback } from "react";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import { Slider } from "antd";
import { NavLink } from "react-router-dom";
import {
  getSizeImage,
  formatMinuteSecond,
  getPlayUrl,
} from "@/utils/format-utils";
import {
  changeCurrentSongAction,
  changeSequenceAction,
  changeCurrentSongsAction,
  changeCurrentLyricIndexAction,
  changeIsBottomMusicAction,
} from "../store/actionCreator";
import { AppPlayerWrapper, Control, PlayInfo, Operator } from "./style";
export default memo(function AppPlayerBar() {
  const audioRef = useRef();
  const [playTime, setTime] = useState(0);
  const [isPlaying, setPlay] = useState(false);
  const [nowTime, setnewTime] = useState(0);
  const [isChange, setIsChange] = useState(false);
  // const [isBottomMusic, setBottomMusic] = useState(true);
  const dispatch = useDispatch();
  const { currentSong, sequence, playList, lyric, lyricIndex, isBottomMusic } =
    useSelector(
      (state) => ({
        currentSong: state.get("player").get("currentSong"),
        sequence: state.get("player").get("sequence"),
        playList: state.get("player").get("playList"),
        lyric: state.get("player").get("lyric"),
        lyricIndex: state.get("player").get("lyricIndex"),
        isBottomMusic: state.get("player").get("isBottomMusic"),
      }),
      shallowEqual
    );
  useEffect(() => {
    dispatch(changeCurrentSongAction(167876));
  }, [dispatch]);

  const picUrl = (currentSong.al && currentSong.al.picUrl) || "";
  const singerName = (currentSong.ar && currentSong.ar[0].name) || "暂无信息";
  const duration = currentSong.dt;
  useEffect(() => {
    audioRef.current.src = getPlayUrl(currentSong.id);
    audioRef.current
      .play()
      .then((res) => {
        setPlay(true);
      })
      .catch((err) => {
        setPlay(false);
      });
  }, [currentSong]);
  const playMusic = useCallback(() => {
    setPlay(!isPlaying);
    isPlaying ? audioRef.current.pause() : audioRef.current.play();
  }, [isPlaying]);
  const changeTime = (e) => {
    const currentTime = e.target.currentTime * 1000;
    if (!isChange) {
      setnewTime((playTime / duration) * 100);
    }
    setTime(e.target.currentTime * 1000);
    let i = 0;
    for (i; i < lyric.length; i++) {
      let musiclyric = lyric[i];
      if (currentTime < musiclyric.time) {
        break;
      }
    }
    //console.log(lyric[i - 1]);

    if (i - 1 !== lyricIndex) {
      //console.log(lyricIndex);
      dispatch(changeCurrentLyricIndexAction(i - 1));
    }
  };
  const onTimeChange = useCallback(
    (e) => {
      //console.log(e);
      const nowPlayTime = (e / 100) * duration;
      setTime(nowPlayTime);
      setIsChange(true);
      setnewTime(e);
      // setTime((nowTime / 100) * duration);
    },
    [duration]
  );
  const afterChange = useCallback(
    (e) => {
      const nowPlayTime = ((e / 100) * duration) / 1000;
      setTime(nowPlayTime * 1000);

      audioRef.current.currentTime = nowPlayTime;
      setIsChange(false);
      if (!isPlaying) {
        playMusic();
      }
    },
    [duration, isPlaying, playMusic]
  );

  const changeSequence = () => {
    switch (sequence) {
      case 1:
        return dispatch(changeSequenceAction(2));
      case 2:
        return dispatch(changeSequenceAction(0));
      default:
        return dispatch(changeSequenceAction(1));
    }
  };
  const changeMusic = (tag) => {
    dispatch(changeCurrentSongsAction(tag));
  };
  const endMusic = (e) => {
    if (sequence === 2 || playList.length === 1) {
      audioRef.current.currentTime = 0;
      audioRef.current.play();
    } else {
      dispatch(changeCurrentSongsAction(1));
    }
  };
  const changeButtomMusic = () => {
    dispatch(changeIsBottomMusicAction(!isBottomMusic));
    //setBottomMusic(!isBottomMusic);
  };
  return (
    <AppPlayerWrapper>
      <div className="content wrap-v2">
        <Control isPlaying={isPlaying}>
          <button
            className="sprite_player prev"
            onClick={(e) => changeMusic(-1)}
          ></button>
          <button
            className="sprite_player play"
            onClick={(e) => playMusic()}
          ></button>
          <button
            className="sprite_player next"
            onClick={(e) => changeMusic(1)}
          ></button>
        </Control>
        <PlayInfo>
          <div className="image">
            <NavLink to="/discover/player">
              <img src={getSizeImage(picUrl, 35)} alt="" />
            </NavLink>
          </div>
          <div className="info">
            <div className="song">
              <span className="song-name">{currentSong.name}</span>
              <a href="ebjcg" className="singer-name">
                {singerName}
              </a>
            </div>
            <div className="progress">
              <Slider
                defaultValue={0}
                value={nowTime}
                onChange={(e) => onTimeChange(e)}
                onAfterChange={(e) => afterChange(e)}
              />
              <div className="time">
                <span className="now-time">{formatMinuteSecond(playTime)}</span>
                <span className="divider">/</span>
                <span className="duration">{formatMinuteSecond(duration)}</span>
              </div>
            </div>
          </div>
        </PlayInfo>
        <Operator sequence={sequence}>
          <div className="left">
            <button className="sprite_playbar btn favor"></button>
            <button className="sprite_playbar btn share"></button>
          </div>
          <div className="right sprite_playbar">
            <button className="sprite_playbar btn volume"></button>
            <button
              className="sprite_playbar btn loop"
              onClick={(e) => changeSequence()}
            ></button>
            <button
              className="sprite_playbar btn playlist"
              onClick={(e) => changeButtomMusic()}
            ></button>
          </div>
        </Operator>
        <audio
          ref={audioRef}
          onTimeUpdate={(e) => changeTime(e)}
          onEnded={(e) => endMusic(e)}
        />
      </div>
    </AppPlayerWrapper>
  );
});
